// Joystick.cpp: implementation of the Joystick class.
//
//////////////////////////////////////////////////////////////////////

#include "Joystick.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Joystick::Joystick()
{
/* JOYSTICK INITILIZATION */
  js = new jsJoystick ( 0 ) ;

  if ( js -> notWorking () || js -> getNumAxes () < 2 )
  {
    #ifdef CONSOLE
    fprintf ( stderr,"No Joystick(0) detected, or number of axis < 2!\n" ) ;
    #else
    ulSetError(UL_WARNING,"No Joystick(0) detected, or number of axis < 2!\n");
    #endif
	this->ok = 0;
  }
  else
  {
  #ifdef CONSOLE    
  fprintf ( stderr,"Joystick (%d) %s with (%d) axes detected.\n",0,js -> getName(),js -> getNumAxes ());
  #endif
  this->ok = 1;
  this->ax = new float [ js->getNumAxes () ] ;
  }
}

Joystick::Joystick(int number)
{
/* JOYSTICK INITILIZATION */
  js = new jsJoystick ( number ) ;

  if ( js -> notWorking () || js -> getNumAxes () < 2 )
  {
    fprintf ( stderr,"No Joystick(%d) detected, or number of axis < 2!\n",number ) ;
	this->ok = 0;
  }
  else
  {
  fprintf ( stderr,"Joystick (%d) %s with (%d) axes detected.\n",number,js -> getName(), js -> getNumAxes ());
  this->ok = 1;
  this->ax = new float [ js->getNumAxes () ] ;
  }
}

Joystick::~Joystick()
{

}

void Joystick::read()
{
	if(this->ok) 
		{
		this->js->read(&(this->buttons),this->ax);
//		printf("Joystick: %x %f %f\n",this->buttons,this->ax[0],this->ax[1]);
		}
}

int Joystick::isPressed(int b)
{
	return this->buttons & b;
}

int Joystick::isDirection(int direction)
{

	if((ax[0] >= 0.2f) && (direction == JOYSTICK_LEFT))
		{
			return 1;
		}
	if((ax[0] <= -0.2f) && (direction == JOYSTICK_RIGHT))
		{
			return 1;
		}
	if((ax[1] <= -0.2f) && (direction == JOYSTICK_UP))
		{
			return 1;
		}
	if((ax[1] >= 0.2f) && (direction == JOYSTICK_DOWN))
		{
			return 1;
		}
	if((ax[0] > -0.2f) && (ax[0] < 0.2f) && (direction == JOYSTICK_H_CENTERED))
		{
			return 1;
		}
	if((ax[1] > -0.2f) && (ax[1] < 0.2f) && (direction == JOYSTICK_V_CENTERED))
		{
			return 1;
		}

return 0;
}

int Joystick::isWorking()
{
	return this->ok;
}

float Joystick::getAX(int n)
{
	return this->ax[n];
}
